package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.check.MaterialModelCheck;
import com.ray.base.service.BaseMaterialModelService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseMaterialModel;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.OrderGoodsBuilder;
import com.ray.business.builder.OrderGoodsVOBuilder;
import com.ray.business.check.OrderCheck;
import com.ray.business.check.OrderGoodsCheck;
import com.ray.business.enums.GoodsStatusEnum;
import com.ray.business.service.ProdOrderGoodsService;
import com.ray.business.service.ProdOrderService;
import com.ray.business.table.dto.OrderGoodsQueryDTO;
import com.ray.business.table.entity.ProdOrder;
import com.ray.business.table.entity.ProdOrderGoods;
import com.ray.business.table.params.order.goods.OrderGoodsQueryParams;
import com.ray.business.table.vo.OrderGoodsVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 订单商品相关服务
 * @Class: OrderGoodsApi
 * @Package com.ray.base.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class OrderGoodsApi {

    @Autowired
    private ProdOrderGoodsService prodOrderGoodsService;
    @Autowired
    private GoodsService goodsService;


    /**
     * 查询订单商品列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<OrderGoodsVO>> pageOrderGoodss(CommonPage<OrderGoodsQueryParams, Page<OrderGoodsVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, MaterialModelVO> goodsMap = new HashMap<>();
        CommonPageBuilder<OrderGoodsQueryDTO, ProdOrderGoods> commonPageBuilder = new CommonPageBuilder<>(OrderGoodsQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdOrderGoods> page = prodOrderGoodsService.page(commonPageBuilder.bulid(), loginUser);
        List<ProdOrderGoods> orders = page.getRecords();
        //结果对象
        IPage<OrderGoodsVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysOrderGoods -> {
                OrderGoodsVOBuilder orderStepBuilder = new OrderGoodsVOBuilder();
                orderStepBuilder.append(sysOrderGoods);
                MaterialModelVO materialModelVO = goodsMap.get(sysOrderGoods.getGoodsCode());
                if (ObjectUtil.isNull(materialModelVO)) {
                    materialModelVO = goodsService.queryGoodsByCode(sysOrderGoods.getGoodsCode(), loginUser);
                    goodsMap.put(sysOrderGoods.getGoodsCode(), materialModelVO);
                }
                orderStepBuilder.append(materialModelVO);
                return orderStepBuilder.bulid();
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }

    /**
     * 查询订单商品列表信息--启用的订单商品
     *
     * @param queryParams
     * @return
     */
    public Result<List<OrderGoodsVO>> queryOrderGoodss(OrderGoodsQueryParams queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, MaterialModelVO> goodsMap = new HashMap<>();
        OrderGoodsQueryDTO queryDTO = new OrderGoodsQueryDTO();
        BeanUtil.copyProperties(queryParams, queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<ProdOrderGoods> orders = prodOrderGoodsService.list(queryDTO, loginUser);
        //查询对象
        List<OrderGoodsVO> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(orders)) {
            list = orders.stream().map(sysOrderGoods -> {
                OrderGoodsVOBuilder orderStepBuilder = new OrderGoodsVOBuilder();
                orderStepBuilder.append(sysOrderGoods);
                MaterialModelVO materialModelVO = goodsMap.get(sysOrderGoods.getGoodsCode());
                if (ObjectUtil.isNull(materialModelVO)) {
                    materialModelVO = goodsService.queryGoodsByCode(sysOrderGoods.getGoodsCode(), loginUser);
                    goodsMap.put(sysOrderGoods.getGoodsCode(), materialModelVO);
                }
                orderStepBuilder.append(materialModelVO);
                return orderStepBuilder.bulid();
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }


    /**
     * 删除订单商品
     *
     * @param code 订单商品编码
     * @return Result
     */
    @Transactional
    public Result<String> deleteOrderGoods(String code) {
        ValidateUtil.hasLength(code, "参数[code]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderGoods sysOrderGoods = prodOrderGoodsService.queryOrderGoodsByOrderCode(code, loginUser);
        new OrderGoodsCheck(sysOrderGoods).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        OrderGoodsBuilder orderBuilder = new OrderGoodsBuilder();
        orderBuilder.appendCode(code).appendEdit(loginUser).delete();
        //删除订单商品信息
        if (!prodOrderGoodsService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("删除订单商品接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 开启订单商品
     *
     * @param code 订单商品编码
     * @return Result
     */
    @Transactional
    public Result<String> openOrderGoods(String code) {
        ValidateUtil.hasLength(code, "参数[code]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderGoods sysOrderGoods = prodOrderGoodsService.queryOrderGoodsByOrderCode(code, loginUser);
        new OrderGoodsCheck(sysOrderGoods).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        OrderGoodsBuilder orderBuilder = new OrderGoodsBuilder();
        orderBuilder.appendCode(code).appendEdit(loginUser).appendStatus(GoodsStatusEnum.PROP.getValue());
        //开启订单商品信息
        if (!prodOrderGoodsService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("开启订单商品接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 开启订单商品
     *
     * @param code 订单商品编码
     * @return Result
     */
    @Transactional
    public Result<String> closeOrderGoods(String code) {
        ValidateUtil.hasLength(code, "参数[code]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderGoods sysOrderGoods = prodOrderGoodsService.queryOrderGoodsByOrderCode(code, loginUser);
        new OrderGoodsCheck(sysOrderGoods).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        OrderGoodsBuilder orderBuilder = new OrderGoodsBuilder();
        orderBuilder.appendCode(code).appendEdit(loginUser).appendStatus(GoodsStatusEnum.UN_PROP.getValue());
        //关闭订单商品信息
        if (!prodOrderGoodsService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("关闭订单商品接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 订单商品详情
     *
     * @param code 订单商品编码
     * @return Result
     */
    public Result<OrderGoodsVO> viewOrderGoods(String code) {
        ValidateUtil.hasLength(code, "参数[code]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderGoods sysOrderGoods = prodOrderGoodsService.queryOrderGoodsByOrderCode(code, loginUser);
        new OrderGoodsCheck(sysOrderGoods).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        OrderGoodsVOBuilder orderStepBuilder = new OrderGoodsVOBuilder();
        orderStepBuilder.append(sysOrderGoods);
        MaterialModelVO materialModelVO = goodsService.queryGoodsByCode(sysOrderGoods.getGoodsCode(), loginUser);
        orderStepBuilder.append(materialModelVO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, orderStepBuilder.bulid());
    }


    /**
     * 订单商品详情
     *
     * @param goodsCode 订单商品编码
     * @return Result
     */
    public Result<OrderGoodsVO> viewOrderGoods(String goodsCode, String orderNo) {
        ValidateUtil.hasLength(goodsCode, "参数[goodsCode]不能为空");
        ValidateUtil.hasLength(orderNo, "参数[orderNo]不能为空");

        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdOrderGoods sysOrderGoods = prodOrderGoodsService.queryOrderGoodsByGoodsCode(orderNo,goodsCode, loginUser);
        new OrderGoodsCheck(sysOrderGoods).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        OrderGoodsVOBuilder orderStepBuilder = new OrderGoodsVOBuilder();
        MaterialModelVO materialModelVO = goodsService.queryGoodsByCode(sysOrderGoods.getGoodsCode(), loginUser);
        orderStepBuilder.append(materialModelVO);
        orderStepBuilder.append(sysOrderGoods);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, orderStepBuilder.bulid());
    }

}
